package com.strongbj.iot.devices.newlight.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.entity.TagUnbind;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.mq.producer.TopicSender;

import cn.hutool.core.date.DateUtil;
import io.netty.channel.ChannelHandlerContext;

public class UnBindTagReturnHandle implements IMessageHandle<NewLightReaderMessage, Object> {
	private static Logger logger = LogManager.getLogger(UnBindTagReturnHandle.class.getName());
	/**
	 * 解绑标签的命令标识
	 */
	private final static byte UNBIND_TAG_COMMAND = Integer.valueOf("4D", 16).byteValue();
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

//	private TagService tagService = (TagService) ContextUtils.getBean("tagService");
	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		return UNBIND_TAG_COMMAND == t.getType();
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		String hostNumber = ByteUtil.bytesToAddress(t.getAddress()); // reader 地址码
		logger.info("收到解绑标签反馈信息 设备编号={} 数据={}", ByteUtil.byteArrToHexString(t.getAddress()),
				ByteUtil.byteArrToHexString(t.getBody()));
		String tagAddress = ByteUtil.bytesToIp(ByteUtil.subBytes(t.getBody(), 0, 4));// LED 标签地址
		NewLightMQMessage mes = new NewLightMQMessage();
		mes.setActioncode("unbindTag");
		mes.setGUID(String.valueOf(DateUtil.date().getTime()));
		TagUnbind tu = new TagUnbind();
		tu.setReaderCode(hostNumber);
		tu.setTag(tagAddress);
		switch (t.getBody()[4]) {
		case 0:
			tu.setUnbindState(TagUnbind.UNBIND_FAIL);
			break;
		case 1:
			tu.setUnbindState(TagUnbind.UNBIND_SUCCESS);
			break;
		case 2:
			tu.setUnbindState(TagUnbind.TAG_NON_EXISTENT);
			break;
		default:
			tu.setUnbindState(TagUnbind.UNKNOWN);
			break;
		}
		mes.setPostdata(tu);
		topicSender.send("wh.reader." + hostNumber + ".message", JSON.toJSONString(mes));
		logger.info("=========unbindTag=======" + JSON.toJSONString(mes));
		return null;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub

	}
}
